﻿using Huasky.MyWrod.Common.Util;
using Microsoft.AspNetCore.Http;

namespace Huasky.MyWrod.Core.Session;

class TokenHelper
{
	/// <summary>
	/// 将token对象转换为http请求中可以携带的字符串
	/// </summary>
	public static string ToTokenString(object value)
	{
		var json   = value.ToJson();
		return AESGcmCrypto.EncryptString(json);
	}
	
	/// <summary>
	/// 从http header中获取token
	/// </summary>
	public static T ParseTokenString<T>(string value)
	{
		if (string.IsNullOrEmpty(value))
			return default;
		
		var json = AESGcmCrypto.DecryptString(value);
		return json.ToObject<T>();
	}

	/// <summary>
	/// 获取Http头中的 Authorization 部分
	/// </summary>
	public static string GetAuthData(HttpRequest request)
	{
		return request.Headers.Authorization.FirstOrDefault();
	}
	
	/// <summary>
	/// 如果以特定前缀开头，则返回后面的子串， 否则返回null
	/// </summary>
	public static string GetSubString(string key, string prefix)
	{
		if (key?.StartsWith(prefix) != true)
		{
			return null;
		}

		return key.Substring(prefix.Length);
	}
}